package org.dromara.tearoom.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.map.MapUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.tearoom.domain.TerCouponTemplate;
import org.dromara.tearoom.domain.bo.TerCouponTemplateBo;
import org.dromara.tearoom.domain.enums.CouponTakeTypeEnum;
import org.dromara.tearoom.domain.vo.TerCouponTemplateVo;
import org.dromara.tearoom.service.ITerCouponService;
import org.dromara.tearoom.service.ITerCouponTemplateService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * 优惠劵模板
 * 前端访问路由地址为:/tearoom/couponTemplate
 *
 * @author ckj
 * @date 2025-04-21
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/couponTemplate")
public class TerCouponTemplateController extends BaseController {

    private final ITerCouponTemplateService terCouponTemplateService;
    private final ITerCouponService terCouponService;

    /**
     * 查询优惠劵模板列表
     */
    @SaCheckPermission("tearoom:couponTemplate:list")
    @GetMapping("/list")
    public TableDataInfo<TerCouponTemplateVo> list(TerCouponTemplateBo bo, PageQuery pageQuery) {
        return terCouponTemplateService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询优惠劵模板列表
     */
    @GetMapping("/appList")
    public TableDataInfo<TerCouponTemplateVo> appList(TerCouponTemplateBo bo, PageQuery pageQuery) {
        bo.setTakeType(CouponTakeTypeEnum.USER.getType());
        TableDataInfo<TerCouponTemplateVo> pageResult=terCouponTemplateService.queryPageList(bo, pageQuery);
        Map<Long, Boolean> canCanTakeMap = terCouponService.getUserCanCanTakeMap(LoginHelper.getAppLoginUser().getId(), pageResult.getRows());
        Map<Long, Boolean> isHaveCouponMap = terCouponService.getUserIsHaveMap(LoginHelper.getAppLoginUser().getId(), pageResult.getRows());
        for (TerCouponTemplateVo template : pageResult.getRows()) {
            // 检查已领取数量是否超过限领数量
            template.setCanTake(MapUtil.getBool(canCanTakeMap, template.getId(), false));
            // 检查用户是否领取优惠券
            template.setIsHave(MapUtil.getBool(isHaveCouponMap, template.getId(), false));
        }
        pageResult.getRows().sort(Comparator.comparing(TerCouponTemplateVo::getIsHave));
        return pageResult;
    }

    /**
     * 导出优惠劵模板列表
     */
    @SaCheckPermission("tearoom:couponTemplate:export")
    @Log(title = "优惠劵模板", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TerCouponTemplateBo bo, HttpServletResponse response) {
        List<TerCouponTemplateVo> list = terCouponTemplateService.queryList(bo);
        ExcelUtil.exportExcel(list, "优惠劵模板", TerCouponTemplateVo.class, response);
    }

    /**
     * 获取优惠劵模板详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("tearoom:couponTemplate:query")
    @GetMapping("/{id}")
    public R<TerCouponTemplateVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable("id") Long id) {
        return R.ok(terCouponTemplateService.queryById(id));
    }

    /**
     * 新增优惠劵模板
     */
    @SaCheckPermission("tearoom:couponTemplate:add")
    @Log(title = "优惠劵模板", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TerCouponTemplateBo bo) {
        return toAjax(terCouponTemplateService.insertByBo(bo));
    }

    /**
     * 修改优惠劵模板
     */
    @SaCheckPermission("tearoom:couponTemplate:edit")
    @Log(title = "优惠劵模板", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TerCouponTemplateBo bo) {
        return toAjax(terCouponTemplateService.updateByBo(bo));
    }

    /**
     * 删除优惠劵模板
     *
     * @param ids 主键串
     */
    @SaCheckPermission("tearoom:couponTemplate:remove")
    @Log(title = "优惠劵模板", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable("ids") Long[] ids) {
        return toAjax(terCouponTemplateService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 优惠劵模板状态修改
     */
    @SaCheckPermission("tearoom:couponTemplate:edit")
    @Log(title = "优惠劵模板状态修改", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R<Void> changeStatus(@RequestBody TerCouponTemplate couponTemplate) {
        return toAjax(terCouponTemplateService.updateCouponStatus(couponTemplate.getId(), couponTemplate.getStatus()));
    }
}
